import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

const routes = [//定义多个一级路由
  {
    path: '/index',
    name: 'index',
    meta: { title: '首页' }, //路由元信息( 会永远保存在当前路由对象身上 )
    component: () => import('../views/Index.vue'),
    children:[//二级路由
      {
        path: '/index/home',
        name: 'home',
        meta: { title: 'home' },
        component: () => import('../views/Index/Home.vue')
      },
      {
        path: '/index/order',
        name: 'order',
        meta: { title: '订单' },
        component: () => import('../views/Index/Order.vue')
      },
      {
        path: '/index/mine',
        name: 'mine',
        meta: { title: '我的' },
        component: () => import('../views/Index/Mine.vue')
      },
      {
        path: '/index/tuan',
        name: 'tuan',
        meta: { title: '抱抱团' },
        component: () => import('../views/Index/Tuan.vue')
      },
      // 二级路由重定向
      {
        path: '/index',
        redirect: '/index/home',
      },
      // 二级404
      {
        path: '*',
        component: () => import('../views/NotFound.vue')
      },
    ]
  },
  {
    path: '/login',
    name: 'login',
    meta: { title : '登录'},
    component: () => import('../views/Login.vue')
  },
  {
    path: '/register',
    name: 'register',
    meta: { title: '注册' },
    component: () => import('../views/Register.vue')
  },
  {
    path: '/detail',
    name: 'detail',
    meta: { title: '注册' },
    component: () => import('../views/Detail.vue')
  },
  // 一级路由重定向
  {
    path: '/',
    redirect: '/index',
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})


// 导航守卫方法
// 路由的全局前置守卫方法(跳任何一个路由都会执行这个方法)
router.beforeEach((to,from,next) => {

  // 动态更新网页标题
  document.title = to.meta.title;

  // 获取localStorage的登录凭证
  let token = localStorage.getItem('token');

  // 跳订单和我的连个页面需要登录
  if (to.path == '/index/order'){
    if(token){
      next()
    }else{
      next('/login')
    }
  }else{
    next()
  }

  if (to.path == '/index/mine') {
    if (token) {
      next()
    } else {
      next('/login')
    }
  } else {
    next()
  }

})






export default router
